<template>
  <el-form
    :model="form"
    ref="form"
    class="clone-bot-form"
    :rules="rules"
    @submit.native.prevent
    @keyup.enter.native="onSave"
    v-loading="loading"
  >
    <el-form-item prop="name" :label="$t('custom.botStore.name')">
      <el-input
        v-model="form.name"
        :maxlength="70"
        show-word-limit
        :placeholder="$t('custom.botStore.enterName')"
      ></el-input>
    </el-form-item>
    <el-form-item prop="roleIdList" :label="$t('custom.reports.role')">
      <el-select
        v-model="form.roleIdList"
        filterable
        clearable
        multiple
        collapse-tags
        default-first-option
        style="width: 100%"
        :placeholder="$t('custom.reports.role')"
      >
        <el-option
          v-for="(item, index) in roleOptions"
          :key="index"
          :value="item.roleId"
          :label="item.name"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item prop="tagList" :label="$t('custom.reports.tag')">
      <el-select
        v-model="form.tagList"
        filterable
        clearable
        multiple
        allow-create
        collapse-tags
        default-first-option
        :placeholder="$t('custom.reports.tag')"
        style="width: 100%"
      >
        <el-option
          v-for="(item, index) in tags"
          :key="index"
          :label="item.name"
          :value="item.name"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item prop="description" :label="$t('custom.botStore.description')">
      <el-input
        v-model="form.description"
        type="textarea"
        :maxlength="500"
        :rows="3"
        show-word-limit
        @keyup.enter.native.stop
        :placeholder="$t('custom.botStore.description')"
      ></el-input>
    </el-form-item>

    <el-form-item class="text-right">
      <el-button size="small" type="primary" @click="onSave">{{
        $t('custom.botStore.save')
      }}</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import {
  fetchTag,
  fetchRole,
  fetchAssignRole,
  fetchBot,
  createBot,
  checkBotName
} from '@/api/new'
import useErrorMessage from '@/components/storybook/hooks/useErrorMessage'
import { intersectionBy } from 'lodash'
import moment from 'moment'
import { symbolReg, parenthesesReg } from '@/components/storybook/utilties/reg'
import {filterRole} from '@/utils/common'
export default {
  name: 'CloneReportForm',
  props: {
    resourceType: [String, Number],
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      form: {
        name: null,
        roleIdList: this.$store.state.defaultRoleList,
        description: null,
        tagList: []
      },
      rules: {
        name: [
          { required: true, validator: this.validateName, trigger: 'blur' },
          {
            min: 0,
            max: 70,
            message: this.$t('custom.tips.valueLength', { length: '70' }),
            trigger: 'blur'
          }
        ],
        roleIdList: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ]
        // description: [
        //   { required: true, message: this.$t('validate.required'), trigger: 'blur' },
        //   { min: 0, max: 499, message: this.$t('custom.tips.valueLength', { length: '500' }), trigger: 'change' }
        // ],
      },

      loading: false,

      tags: [],
      roleOptions: []
    }
  },

  created() {
    this.init()
  },
  methods: {
    async init() {
      try {
        this.loading = true
        const [roles, tags, assignRoles, bot] = await Promise.all([
          this.getRoles(),
          this.getTags(),
          this.getAssingRoles(),
          this.getBot()
        ])
        this.roles = roles
        this.tags = tags

        const assigns = assignRoles.map(item => ({
          ...item,
          roleId: item.assignId
        }))
        this.roleOptions = intersectionBy(this.roles, assigns, 'roleId')

        const {
          roleIdList,
          id,
          name,
          description,
          status,
          tagList,
          businessType
        } = bot

        this.form = {
          businessType:
            businessType === 'MSPbots Internal' ? businessType : 'Custom',
          tenantCode: this.$store.state.user.tenantCode,
          roleIdList: await filterRole(roleIdList),
          originalId: id,
          newType: 3,
          description,
          status,
          tagList,
          resourceType: this.resourceType,
          name: null
        }

        this.form.name = `${name} (clone at ${moment().utc().format()})`

        if (name.match(parenthesesReg)) {
          this.form.name = name.replace(
            parenthesesReg,
            `(clone at ${moment().utc().format()})`
          )
        }
      } catch (error) {
      } finally {
        this.loading = false
      }
    },

    async validateName(rule, value, callback) {
      if (!value) {
        throw new Error(this.$t('validate.required'))
      }
      try {
        const { name, id } = this.form
        let params = {
          name,
          id
        }
        if (!symbolReg.test(value)) {
          throw new Error(this.$t('validate.isIncludeSymbol'))
        }

        const { data: response } = await checkBotName(params)
        if (response.code !== 0) {
          throw new Error('The name is already exists')
        }
        callback()
      } catch (error) {
        callback(error)
      }
    },

    async getRoles() {
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      const { data: response } = await fetchRole(params)
      if (response.code !== 0) {
        return []
      }
      return response.data || []
    },
    async getAssingRoles() {
      const roleIds = (this.$store.state.user.roleList || []).map(
        ({ id }) => id
      )
      const params = {
        roleId: roleIds
      }
      const { data: response } = await fetchAssignRole(params)
      if (response.code !== 0) {
        return []
      }
      return response.data || []
    },
    async getTags() {
      const params = {}
      const { data: response } = await fetchTag(params)
      if (response.code !== 0) {
        return []
      }
      return response.data || []
    },

    async getBot() {
      const { data: response } = await fetchBot({ id: this.id })
      if (response.code !== 0) {
        return {}
      }
      return response.data || {}
    },

    async onSave() {
      try {
        this.loading = true

        await this.$refs['form'].validate()

        const params = {
          ...this.form
        }

        const { data: response } = await createBot(params)
        if (response.code !== 0) {
          throw response.msg
        }
        this.$message.success(response.msg)
        this.$emit('event:success', response.data || {})
      } catch (error) {
        useErrorMessage(error)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>
